#include <iostream>
#include <vector>
#include "lib/list.h"
using namespace std;

// head_node是二级指针，这样才可以改变head_node
void deleteNode(ListNode** head_node, ListNode* delete_node) {
  if (delete_node == nullptr ||
      head_node == nullptr ||
      *head_node == nullptr) {
    return;
  }

  auto next_node = delete_node->next;
  if (next_node) {
    delete_node->value = next_node->value;
    delete_node->next = next_node->next;
    delete next_node;
    next_node = nullptr;
  } else if (*head_node == delete_node) {
    delete delete_node;
    delete_node = nullptr;
    *head_node = nullptr;
  } else {
    next_node = *head_node;
    while (next_node->next != delete_node) {
      next_node = next_node->next;
    }
    next_node->next = nullptr;
    delete delete_node;
    delete_node = nullptr;
  }
}

int main() {
  vector<int> vec_node = {0, 1, 2, 3, 4, 5};
  auto head_node = CreateList(vec_node);

  // 0, 1, 2, 3, 4, 5 delete_node = 3
  auto delete_node = head_node;
  while (delete_node->value != 3) {
    delete_node = delete_node->next;
  }
  cout << "Delete intermedia node" << endl;
  deleteNode(&head_node, delete_node);
  PrintList(head_node);
  
  // 0, 1, 2, 4, 5 delete_node = 0
  delete_node = head_node;
  cout << "Delete head node" << endl;
  deleteNode(&head_node, head_node);
  PrintList(head_node);

  // 1, 2, 4, 5 delete_node = 5
  delete_node = head_node;
  while (delete_node->value != 5) {
    delete_node = delete_node->next;
  }
  cout << "Delete tail node" << endl;
  deleteNode(&head_node, delete_node);
  PrintList(head_node);

  // 1, 2, 4 delete_node = 4
  delete_node = head_node;
  while (delete_node->value != 4) {
    delete_node = delete_node->next;
  }
  cout << "Delete tail node" << endl;
  deleteNode(&head_node, delete_node);
  PrintList(head_node);

  // 1, 2 delete_node = 1
  delete_node = head_node;
  cout << "Delete head node" << endl;
  deleteNode(&head_node, head_node);
  PrintList(head_node);

  return 0;
}
